package com.dhms.vostok1.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.GridLayout
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.dhms.workbench.databinding.WorkBenchItemBinding
import com.dhms.workbench.databinding.WorkBenchItemContentBinding
import com.dhms.vostok1.data.work_bench.WorkBenchData
import com.dhms.vostok1.data.work_bench.WorkBenchItem

class WorkBenchListAdapter(private val onItemClick: (itemData: WorkBenchItem) -> Unit) :
    ListAdapter<WorkBenchData, WorkBenchListAdapter.WorkBenchListViewHolder>(
        DiffCallback
    ) {

    class WorkBenchListViewHolder(var binding: WorkBenchItemBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bind(item: WorkBenchData, onItemClick: (itemData: WorkBenchItem) -> Unit) {
            binding.item = item
            addGridItem(item, onItemClick)
            binding.executePendingBindings()
        }

        private fun addGridItem(
            item: WorkBenchData,
            onItemClick: (itemData: WorkBenchItem) -> Unit
        ) {
            /*添加item*/
            val grid = binding.workBenchGirdWrapper
            grid.removeAllViews()

            item.items?.forEach { data ->

                val layoutParams = GridLayout.LayoutParams()
                layoutParams.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, GridLayout.FILL, 1f)
                val itemContent =
                    WorkBenchItemContentBinding.inflate(LayoutInflater.from(grid.context))
                itemContent.linearWrapper.layoutParams = layoutParams
                itemContent.item = data
                grid.addView(itemContent.root)

                if (data.itemType != null) {
                    itemContent.linearWrapper.setOnClickListener {
                        onItemClick(data)
                    }
                }

            }
        }
    }

    companion object DiffCallback : DiffUtil.ItemCallback<WorkBenchData>() {
        override fun areItemsTheSame(
            oldItem: WorkBenchData,
            newItem: WorkBenchData
        ): Boolean {
            return oldItem.title == newItem.title
        }

        override fun areContentsTheSame(
            oldItem: WorkBenchData,
            newItem: WorkBenchData
        ): Boolean {
            return oldItem == newItem
        }
    }

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): WorkBenchListViewHolder {
        return WorkBenchListViewHolder(
            WorkBenchItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        )
    }

    override fun onBindViewHolder(holder: WorkBenchListViewHolder, position: Int) {
        val item = getItem(position)
        holder.bind(item, onItemClick)
    }

}